/**
 * 
 */
package me.joshua.demo4j.spring.context.profile;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author <a href="mailto:daonan.zhan@gmail.com">Joshua Zhan</a>
 *
 */
public abstract class ContextUtils {

	private static ThreadLocal<ConfigurableApplicationContext>	localContext	= new ThreadLocal<ConfigurableApplicationContext>();
	
	public static String[] getConfigArray(String... configs) {
		return configs;
	}
	public static Class<?>[] getConfigArray(Class<?>... configs) {
		return configs;
	}

	public static ConfigurableApplicationContext loadContext(String[] configs, String... profiles) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configs, false);
		return doLoadContext(context, profiles);
	}

	public static ConfigurableApplicationContext loadContext(Class<?>[] configs, String... profiles) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(configs);
		context.getEnvironment().setActiveProfiles(profiles);
		context.refresh();
		localContext.set(context);
		return context;
//		return doLoadContext(context, profiles);
	}
	
	private static ConfigurableApplicationContext doLoadContext(ConfigurableApplicationContext context, String... profiles) {
		context.getEnvironment().setActiveProfiles(profiles);
		context.refresh();
		localContext.set(context);
		return context;
	}
	
	public static void closeLocal() {
		ConfigurableApplicationContext context = localContext.get();
		if (null != context && context.isActive()) {
			context.close();
		}
	}
}
